//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.app.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.live.configuration.SessionInfo;
import com.ruoyi.live.exam.service.LiveExamJudgeService;
import com.ruoyi.live.exam.service.LiveExamService;
import com.ruoyi.live.base.domain.*;
import com.ruoyi.live.base.mapper.*;
import com.ruoyi.live.base.domain.vo.BarrageParam;
import com.ruoyi.live.base.domain.vo.TaskUserVO;
import com.ruoyi.live.base.service.impl.LiveTaskUserDetailServiceImpl;
import com.ruoyi.live.product.service.LiveBarrageService;
import com.ruoyi.live.tool.commons.ICommons;
import com.ruoyi.live.tool.commons.IConvert;
import com.ruoyi.live.tool.commons.IMD5;
import com.ruoyi.live.tool.utils.Message;
import com.ruoyi.live.tool.utils.NameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AppService {
    private static final Logger log = LoggerFactory.getLogger(AppService.class);
    @Autowired
    LiveExamMapper examDao;
    @Autowired
    LiveExamTaskMapper taskDao;
    @Autowired
    LiveExamUserMapper examUserDao;
    @Autowired
    LiveTaskUserMapper taskUserDao;
    @Autowired
    LiveTaskUserDetailMapper detailDao;
    @Autowired
    LiveTaskUserDetailServiceImpl detailService;
    @Autowired
    LiveProductMapper productDao;
    @Autowired
    LiveProductSourceMapper sourceDao;
    @Autowired
    LiveServerMapper serverDao;
    @Autowired
    LiveTaskUserChannelMapper channelMapper;
    @Autowired
    CacheService cacheService;
    @Autowired
    LiveBarrageService lbcService;

    @Autowired
    UserMapper userDao;
    @Autowired
    LiveTaskUserPutMapper putDao;
    @Autowired
    LiveProductItemMapper itemDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    LiveBarrageChannelMapper barrageChannelMapper;
    @Autowired
    LiveTaskUserChannelReconnectMapper reconnectDao;
    @Autowired
    LiveExamService liveExamService;
    @Autowired
    VideoService videoService;
    @Autowired
    LiveExamJudgeService liveExamJudgeService;
    @Autowired
    LiveBarrageMapper barrageMapper;
    private static Integer channelIndex = 0;
    private static Integer channelIndexWeb = 0;

    public AppService() {
    }

    public List<LiveExam> examList() {
        return this.examDao.getUserExam(SessionInfo.getUserId(), SessionInfo.getUser().getClassId());
    }

    public Message getUserInfoByToken() {
        User user = (User)this.userDao.selectById(SessionInfo.getUserId());
        user.setUserPasswordMd5((Long)null);
        user.setUserLoginNameMd5((Long)null);
        user.setUrlPath(OpenService.urlPath);
        return new Message(true, JSON.toJSONString(user));
    }

    public List<LiveExamTask> doTaskList(Long id) {
        List<LiveExamTask> list = this.taskUserDao.getUserTasks(SessionInfo.getUserId(), id);
        Iterator iterator = list.iterator();

        while(true) {
            LiveExamTask task;
            List channels;
            do {
                do {
                    do {
                        if (!iterator.hasNext()) {
                            return list;
                        }

                        task = (LiveExamTask)iterator.next();
                    } while(task.getTaskType() != 2);
                } while(task.getTaskUserState() == 1);

                channels = this.channelMapper.selectList((Wrapper)(new QueryWrapper((new LiveTaskUserChannel()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(task.getTaskUserId()))).orderByAsc("create_time"));
            } while(channels.size() <= 0);

            LiveTaskUserChannel channel = (LiveTaskUserChannel)channels.get(channels.size() - 1);
            if (channel.getState() == 1) {
                this.channelMapper.updateById(channel.setState(2).setEndTime(System.currentTimeMillis()));
            }

            Iterator var7 = channels.iterator();

            while(var7.hasNext()) {
                LiveTaskUserChannel cnl = (LiveTaskUserChannel)var7.next();

                try {
                    if (cnl.getEndTime() == null) {
                        cnl.setState(3);
                        this.channelMapper.updateById((new LiveTaskUserChannel()).setState(3).setId(cnl.getId()));
                    } else {
                        cnl.setDelayTime(getDelayTime(cnl.getCreateTime(), cnl.getEndTime()));
                    }
                } catch (Exception var10) {
                    var10.printStackTrace();
                }
            }

            task.setChannels(channels);
        }
    }

    public Message doStartExam(Long id, Long userId) throws Exception {
        if (userId == null) {
            userId = SessionInfo.getUserId();
        }

        if (ICommons.isNullOrEmpty(userId)) {
            throw new Exception("获取用户数据失败");
        } else {
            LiveExam exam = (LiveExam)this.examDao.selectById(id);
            if (exam == null) {
                throw new Exception("获取比赛失败");
            } else {
                List<LiveExamTask> list = this.taskDao.selectList((Wrapper)(new QueryWrapper((new LiveExamTask()).setExamId(id))).orderByAsc("task_order"));
                if (list.size() == 0) {
                    throw new Exception("获取任务失败");
                } else {
                    try {
                        LiveExamUser examUser = (LiveExamUser)this.examUserDao.selectOne(new QueryWrapper((new LiveExamUser()).setExamId(id).setCreateUser(userId)));
                        if (examUser == null) {
                            Long taskCount = this.taskDao.selectCount(new QueryWrapper((new LiveExamTask()).setExamId(id)));
                            examUser = (new LiveExamUser()).setCreateTime(System.currentTimeMillis()).setCreateUser(userId).setState(2).setDoneCount(0).setTaskCount(taskCount.intValue()).setExamDuration(exam.getExamDuration()).setExamId(exam.getId()).setTimeUserd(0);
                            this.examUserDao.insert(examUser);

                            for(int i = 0; i < list.size(); ++i) {
                                LiveExamTask task = (LiveExamTask)list.get(i);
                                Long productId = null;
                                if (task.getTaskType() == 1) {
                                    if (task.getTaskProductType() == 1) {
                                        List<Long> ids = this.productDao.getIdsList(id);
                                        productId = (Long)ids.get((new Random()).nextInt(ids.size()));
                                    } else {
                                        productId = task.getTaskProductId();
                                    }
                                }

                                LiveTaskUser taskUser = (new LiveTaskUser()).setCreateTime(System.currentTimeMillis()).setCreateUser(userId).setExamId(task.getExamId()).setLeuId(examUser.getId()).setProductId(productId).setState(1).setHasConnect(1).setTaskDuration(task.getTaskDuration()).setTaskId(task.getId()).setTaskOrder(task.getTaskOrder()).setTaskProcudtCount(task.getTaskCount()).setTaskProcudtCountUsed(0).setTaskProgress(0).setTaskQuestionAnswerCount(0).setTaskType(task.getTaskType());
                                if (i == 0) {
                                    taskUser.setState(2);
                                }

                                this.taskUserDao.insert(taskUser);
                            }
                        }

                        return new Message(true, examUser.getId().toString());
                    } catch (Exception var11) {
                        var11.printStackTrace();
                        log.error("初始化比赛失败", var11);
                        throw new Exception("初始化比赛失败");
                    }
                }
            }
        }
    }

    public LiveExamUser getExamUser(Long id) {
        LiveExamUser examUser = (LiveExamUser)this.examUserDao.selectOne(new QueryWrapper((new LiveExamUser()).setExamId(id).setCreateUser(SessionInfo.getUserId())));
        examUser.setTimeUserd(0);
        return examUser;
    }

    public List<LiveProductSource> getImages(Long id, Integer type) {
        return this.sourceDao.selectList(new QueryWrapper((new LiveProductSource()).setProductId(id).setSourceType(type)));
    }

    public void saveTaskDetail(String banners, String title, String contents, Long taskUserId) throws Exception {
        String[] bannerArr = banners.split(",");
        String[] contentArr = contents.split(",");
        JSONObject object = JSONObject.parseObject(title);
        if (bannerArr.length == 0) {
            throw new Exception("请设置轮播图");
        } else if (contentArr.length == 0) {
            throw new Exception("请设置内容图");
        } else {
            this.detailDao.delete(new QueryWrapper((new LiveTaskUserDetail()).setTaskUserId(taskUserId)));
            List<LiveTaskUserDetail> res = new ArrayList();

            int i;
            LiveTaskUserDetail detail;
            for(i = 0; i < bannerArr.length; ++i) {
                detail = (new LiveTaskUserDetail()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setProductSourceId(IConvert.object2long(bannerArr[i])).setTaskUserId(taskUserId).setDetailOrder(i + 1).setDetailType(1);
                res.add(detail);
            }

            for(i = 0; i < contentArr.length; ++i) {
                detail = (new LiveTaskUserDetail()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setProductSourceId(IConvert.object2long(contentArr[i])).setTaskUserId(taskUserId).setDetailOrder(i + 1).setDetailType(2);
                res.add(detail);
            }

            res.add((new LiveTaskUserDetail()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setTaskUserId(taskUserId).setDetailOrder(1).setDetailType(3).setDetailContent(IConvert.object2string(object.get("title"))));
            res.add((new LiveTaskUserDetail()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setTaskUserId(taskUserId).setDetailOrder(1).setDetailType(4).setDetailContent(IConvert.object2string(object.get("price"))));
            res.add((new LiveTaskUserDetail()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setTaskUserId(taskUserId).setDetailOrder(1).setDetailType(5).setDetailContent(IConvert.object2string(object.get("scale"))));

            try {
                this.detailService.saveBatch(res);
            } catch (Exception var11) {
                var11.printStackTrace();
                throw new Exception("保存失败");
            }
        }
    }

    public TaskUserVO getTaskDetail(Long id) {
        List<LiveTaskUserDetail> list = this.detailDao.selectList((Wrapper)((QueryWrapper)(new QueryWrapper((new LiveTaskUserDetail()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(id))).orderByAsc("detail_type")).orderByAsc("detail_order"));
        TaskUserVO res = new TaskUserVO();
        List<Long> bannerIds = new ArrayList();
        List<Long> contentIds = new ArrayList();
        Iterator var6 = list.iterator();

        while(var6.hasNext()) {
            LiveTaskUserDetail detail = (LiveTaskUserDetail)var6.next();
            switch(detail.getDetailType()) {
                case 1:
                    bannerIds.add(detail.getProductSourceId());
                    break;
                case 2:
                    contentIds.add(detail.getProductSourceId());
                    break;
                case 3:
                    res.setTitle(detail.getDetailContent());
                    break;
                case 4:
                    res.setPrice(detail.getDetailContent());
                    break;
                case 5:
                    res.setScale(detail.getDetailContent());
            }
        }

        if (bannerIds.size() > 0) {
            res.setBanners(this.sourceDao.selectListByIds(bannerIds));
        }

        res.setContents(this.sourceDao.getSourcesByTaskUserId(id));
        return res;
    }

    public void doSubmitTask(Long id) {
        LiveTaskUser ltu = (LiveTaskUser)this.taskUserDao.selectById(id);
        if (ltu.getState() != 3) {
            this.taskUserDao.updateById((new LiveTaskUser()).setId(id).setState(3));
            LiveTaskUser next = (LiveTaskUser)this.taskUserDao.selectOne(new QueryWrapper((new LiveTaskUser()).setTaskOrder(ltu.getTaskOrder() + 1).setCreateUser(SessionInfo.getUserId()).setExamId(ltu.getExamId()).setLeuId(ltu.getLeuId())));
            if (next != null) {
                this.taskUserDao.updateById(next.setState(2));
            }

            LiveExamUser leu = (LiveExamUser)this.examUserDao.selectById(ltu.getLeuId());
            this.examUserDao.updateById(leu.setDoneCount(leu.getDoneCount() + 1));
        }

    }

    public static void main(String[] args) {
        for(int i = 0; i <= 10; ++i) {
            System.out.println(i % 3);
        }

    }

    public Message doSetChannel(Long taskUserId, Long channelId, String filename) {
        List<LiveServer> servers = this.serverDao.selectList(new QueryWrapper((new LiveServer()).setState(1)));
        if (servers.size() == 0) {
            return new Message(false, "分配直播间失败");
        } else {
            LiveServer server = null;

            try {
                server = (LiveServer)servers.get(channelIndex % servers.size());
                Integer var6 = channelIndex;
                channelIndex = channelIndex + 1;
            } catch (Exception var13) {
                var13.printStackTrace();
                server = (LiveServer)servers.get(0);
            }

            LiveTaskUser taskUser = (LiveTaskUser)this.taskUserDao.selectById(taskUserId);
            if (taskUser == null) {
                return new Message(false, "任务获取失败");
            } else if (!taskUser.getCreateUser().equals(SessionInfo.getUserId())) {
                return new Message(false, "不能开始别人的任务");
            } else {
                String channelName = UUID.randomUUID().toString().replaceAll("-", "");
                LiveTaskUserChannel channel = null;
                if (!ICommons.isNullOrEmpty(channelId, true) && channelId != 0L) {
                    channel = (LiveTaskUserChannel)this.channelMapper.selectById(channelId);
                    channelName = channel.getChannelName();
                } else {
                    this.taskUserDao.updateById(taskUser.setTaskProcudtCountUsed(taskUser.getTaskProcudtCountUsed() + 1));
                    List<LiveTaskUserChannel> channels = this.channelMapper.selectList(new QueryWrapper((new LiveTaskUserChannel()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(taskUserId)));
                    Integer order = channels.size() + 1;
                    channel = (new LiveTaskUserChannel()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(taskUserId).setExamUserId(taskUser.getLeuId()).setState(1).setStoreFileName(filename).setExamId(taskUser.getExamId()).setTaskId(taskUser.getTaskId()).setChannelName(channelName).setChannelOrder(order).setChannelType(1).setTimeUsed(0).setServerId(server.getId()).setFilePath(server.getFilePath());

                    try {
                        this.channelMapper.insert(channel);
                    } catch (Exception var12) {
                        var12.printStackTrace();
                        throw var12;
                    }
                }

                String url = "rtmp://" + server.getServerIp() + ":" + server.getServerPort() + "/mapper/" + channelName;
                Map<String, Object> res = new HashMap();
                res.put("url", url);
                res.put("id", channel.getId());
                return new Message(true, url, JSON.toJSONString(channel));
            }
        }
    }

    public Message doSetChannelWeb(Long taskUserId, Long channelId) {
        List<LiveServer> servers = this.serverDao.selectList(new QueryWrapper((new LiveServer()).setState(2)));
        if (servers.size() == 0) {
            servers = this.serverDao.selectList(new QueryWrapper((new LiveServer()).setState(1)));
        }

        if (servers.size() == 0) {
            return new Message(false, "分配直播间失败");
        } else {
            LiveServer server = null;

            try {
                server = (LiveServer)servers.get(channelIndexWeb % servers.size());
                Integer var5 = channelIndexWeb;
                channelIndexWeb = channelIndexWeb + 1;
            } catch (Exception var12) {
                var12.printStackTrace();
                server = (LiveServer)servers.get(0);
            }

            LiveTaskUser taskUser = (LiveTaskUser)this.taskUserDao.selectById(taskUserId);
            if (taskUser == null) {
                return new Message(false, "任务获取失败");
            } else if (!taskUser.getCreateUser().equals(SessionInfo.getUserId())) {
                return new Message(false, "不能开始别人的任务");
            } else {
                String channelName = UUID.randomUUID().toString().replaceAll("-", "");
                LiveTaskUserChannel channel = null;
                if (!ICommons.isNullOrEmpty(channelId, true) && channelId != 0L) {
                    channel = (LiveTaskUserChannel)this.channelMapper.selectById(channelId);
                    channelName = channel.getChannelName();
                } else {
                    this.taskUserDao.updateById(taskUser.setTaskProcudtCountUsed(taskUser.getTaskProcudtCountUsed() + 1));
                    List<LiveTaskUserChannel> channels = this.channelMapper.selectList(new QueryWrapper((new LiveTaskUserChannel()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(taskUserId)));
                    Integer order = channels.size() + 1;
                    channel = (new LiveTaskUserChannel()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(taskUserId).setExamUserId(taskUser.getLeuId()).setState(1).setExamId(taskUser.getExamId()).setTaskId(taskUser.getTaskId()).setChannelName(channelName).setChannelOrder(order).setChannelType(1).setTimeUsed(0).setServerId(server.getId()).setFilePath(server.getFilePath());

                    try {
                        this.channelMapper.insert(channel);
                    } catch (Exception var11) {
                        var11.printStackTrace();
                        throw var11;
                    }
                }

                String url = "rtmp://" + server.getServerIp() + ":" + server.getServerPort() + "/mapper/" + channelName;
                Map<String, Object> res = new HashMap();
                res.put("url", url);
                res.put("id", channel.getId());
                return new Message(true, url, JSON.toJSONString(channel));
            }
        }
    }

    public void doStartLiveTask(Long taskUserId, HttpServletRequest request) throws Exception {
        LiveTaskUser taskUser = (LiveTaskUser)this.taskUserDao.selectById(taskUserId);
        if (taskUser == null) {
            throw new Exception("开始任务失败");
        } else if (!taskUser.getCreateUser().equals(SessionInfo.getUserId())) {
            throw new Exception("不能开始别人的任务");
        } else if (taskUser.getTaskProcudtCount() <= taskUser.getTaskProcudtCountUsed()) {
            throw new Exception("任务次数使用完毕");
        } else {
            List<LiveTaskUserChannel> channels = this.channelMapper.selectList((Wrapper)(new QueryWrapper((new LiveTaskUserChannel()).setCreateUser(SessionInfo.getUserId()).setTaskUserId(taskUserId))).orderByDesc("create_time"));
            if (channels.size() > 0) {
                LiveTaskUserChannel channel = (LiveTaskUserChannel)channels.get(0);
                if (channel.getState() == 1) {
                    this.channelMapper.updateById(channel.setState(2));
                }
            }

        }
    }

    public void doEndLive(HttpServletRequest request, Long id, Long examUserId) throws Exception {
        LiveTaskUserChannel channel = (LiveTaskUserChannel)this.channelMapper.selectById(id);
        if (channel == null) {
            throw new Exception("找不到这个视频");
        } else if (!channel.getCreateUser().equals(SessionInfo.getUserId())) {
            throw new Exception("不能关闭别人的任务");
        } else {
            if (channel.getState() == 1) {
                this.channelMapper.updateById(channel.setState(2).setEndTime(System.currentTimeMillis()));
                String filePath = request.getSession().getServletContext().getRealPath("");
                this.videoService.getLiveVideoInfo(id, filePath, channel.getServerId(), channel.getChannelName());
            }

        }
    }

    public Message getVideoUrl(Long id, HttpServletRequest request) {
        return new Message(true, "");
    }

    public static String getDelayTime(Long start, Long end) {
        Long time = (end - start) / 1000L;
        Long minute = (time - time % 60L) / 60L;
        Long second = time % 60L;
        return (minute > 0L ? minute + "分" : "") + second + "秒";
    }

    public Message hasVideo(Long id, HttpServletRequest request) {
        LiveTaskUserChannel channel = (LiveTaskUserChannel)this.channelMapper.selectById(id);
        String path = request.getSession().getServletContext().getRealPath(channel.getFilePath());
        String fileName = channel.getChannelName() + ".flv.info";
        File file = new File(path + fileName);
        return file.exists() ? new Message(false, "正在转码中,请稍后") : new Message(true, channel.getFilePath() + channel.getChannelName() + ".flv");
    }

    public Message doGetBarrage(BarrageParam param) {
        Long id = param.getId();
        Integer index = param.getIndex();
        Integer start = param.getStart();
        Long taskUserId = param.getTaskUserId();
        Integer productIndex = param.getProductIndex();
        Integer barrageIndex = param.getBarrageIndex();
        Long productId = param.getProductId();
        List<LiveBarrage> result = new ArrayList();
        result.add(this.getOneCustomBarrage(id, index));
        LiveExamTask task = this.cacheService.getExamByChannelId(id);
        if (!ICommons.isNullOrEmpty(productId) && task.getTaskQuestionDelay() != null && task.getTaskQuestionInterval() != null && (index - start >= task.getTaskQuestionDelay() || index >= 240 * (productIndex + 1)) && ((index - task.getTaskQuestionDelay()) % task.getTaskQuestionInterval() == 0 || start == index && index != 0) && barrageIndex < task.getTaskQuestionCount()) {
            result.add(this.getOneQuestionBarrage(id, index, task.getTaskQuestionStay(), barrageIndex, productId, taskUserId));
        }

        return new Message(true, JSONArray.of(result).toString());
    }

    public LiveBarrage getOneCustomBarrage(Long id, Integer index) {
        List<LiveBarrage> list = this.cacheService.customBarrageList();
        Random rand = new Random();
        LiveBarrage res = (LiveBarrage)list.get(rand.nextInt(list.size()));
        int addCount = rand.nextInt(20);
        int level = rand.nextInt(10) + rand.nextInt(10);
        String userName = NameUtil.randomName();
        this.lbcService.addOneBarrage(id, index, res, addCount, level, userName);
        res.setAddCount(addCount);
        res.setUserName(userName);
        res.setLevel(level);
        return res;
    }

    public LiveBarrage getOneGiftBarrage(Long id, Integer index) {
        List<LiveBarrage> list = this.cacheService.giftBarrageList();
        Random rand = new Random();
        LiveBarrage res = (LiveBarrage)list.get(rand.nextInt(list.size()));
        int addCount = rand.nextInt(20) - 5;
        int level = rand.nextInt(10) + rand.nextInt(10);
        String userName = NameUtil.randomName();
        this.lbcService.addOneBarrage(id, index, res, addCount, level, userName);
        res.setAddCount(addCount);
        res.setUserName(userName);
        res.setLevel(level);
        return res;
    }

    public LiveBarrage getOneQuestionBarrage(Long id, Integer index, Integer stay, Integer barrageIndex, Long productId, Long taskUserId) {
        Random rand = new Random();
        List<LiveBarrage> list = this.cacheService.questionBarrageList(productId);
        LiveBarrage res = (LiveBarrage)list.get(rand.nextInt(list.size()));
        List<LiveBarrageChannel> has = this.barrageChannelMapper.selectList(new QueryWrapper((new LiveBarrageChannel()).setChannelId(id).setType(5)));
        if (has.size() > 0) {
            for(List ids = (List)has.stream().map((lbc) -> {
                return lbc.getBarrageId();
            }).collect(Collectors.toList()); ids.contains(res.getId()); res = (LiveBarrage)list.get(rand.nextInt(list.size()))) {
                ;
            }
        }

        res.setStayTime(stay);
        int addCount = rand.nextInt(20) - 5;
        int level = rand.nextInt(10) + rand.nextInt(10);
        String userName = NameUtil.randomName();
        this.lbcService.addOneBarrage(id, index, res, addCount, level, userName);
        res.setAddCount(addCount);
        res.setUserName(userName);
        res.setLevel(level);
        res.setStayTime(stay);
        this.taskUserDao.updateCount(taskUserId);
        return res;
    }

    public List<Map<String, Object>> getGifts() {
        String[] strs = new String[]{"1.svga", "2.svga", "3.svga", "4.svga", "5.svga", "6.svga", "7.svga"};
        List<Map<String, Object>> res = new ArrayList();
        String[] var3 = strs;
        int var4 = strs.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String str = var3[var5];
            Map<String, Object> kv = new HashMap();
            kv.put("name", str);
            kv.put("path", "");
            res.add(kv);
        }

        return res;
    }

    public void doSetLastVideo(Long id) {
        LiveTaskUserChannel channel = (LiveTaskUserChannel)this.channelMapper.selectById(id);
        this.channelMapper.update((new LiveTaskUserChannel()).setChannelType(1), new UpdateWrapper((new LiveTaskUserChannel()).setTaskUserId(channel.getTaskUserId())));
        this.channelMapper.updateById((new LiveTaskUserChannel()).setChannelType(2).setId(id));
        this.doSubmitTask(channel.getTaskUserId());
    }

    public void startExam(Long id) {
        this.examUserDao.updateById((new LiveExamUser()).setId(id).setState(2));
    }

    public void saveTime(Long id, Integer index) {
        this.examUserDao.updateById((new LiveExamUser()).setTimeUserd(index).setId(id));
    }

    public void doEndExam(Long id) {
        LiveExamUser eu = (LiveExamUser)this.examUserDao.selectById(id);
        this.examUserDao.updateById((new LiveExamUser()).setId(id).setState(3).setDoneCount(eu.getTaskCount()));
        this.taskUserDao.update((new LiveTaskUser()).setState(3), new UpdateWrapper((new LiveTaskUser()).setLeuId(id)));

        try {
            LiveTaskUser tu = (LiveTaskUser)this.taskUserDao.selectOne(new QueryWrapper((new LiveTaskUser()).setTaskType(2).setLeuId(id)));
            if (tu != null) {
                LiveTaskUserChannel one = (LiveTaskUserChannel)this.channelMapper.selectOne((Wrapper)((QueryWrapper)((QueryWrapper)(new QueryWrapper()).eq("state", 2)).eq("channel_type", 2)).eq("task_user_id", tu.getId()));
                if (one == null) {
                    List<LiveTaskUserChannel> lasts = this.channelMapper.selectList((Wrapper)((QueryWrapper)((QueryWrapper)(new QueryWrapper()).eq("state", 2)).orderByDesc("create_time")).eq("task_user_id", tu.getId()));
                    if (lasts.size() > 0) {
                        LiveTaskUserChannel last = (LiveTaskUserChannel)lasts.get(0);
                        this.channelMapper.updateById((new LiveTaskUserChannel()).setId(last.getId()).setChannelType(2));
                    }
                }
            }

            try {
                this.liveExamService.doCountObjScore(id);
            } catch (Exception var7) {
                var7.printStackTrace();
            }

            this.liveExamJudgeService.doSaveJudge(eu);
        } catch (Exception var8) {
            var8.printStackTrace();
            log.error("{}交卷失败:id为{}", new Object[]{SessionInfo.getUserId(), id, var8});
        }

    }

    public void doUserRePass(String passOld, String passNew) throws Exception {
        User user = SessionInfo.getUser();
        if (ICommons.isNullOrEmpty(user.getUserPasswordMd5())) {
            throw new Exception("修改失败");
        } else if (user.getUserPasswordMd5().equals(IMD5.getMD5(passOld))) {
            try {
                this.userDao.updateById((new User()).setId(user.getId()).setUserPasswordMd5(IMD5.getMD5(passNew)));
            } catch (Exception var5) {
                var5.printStackTrace();
                throw new Exception("修改失败");
            }
        } else {
            throw new Exception("原输入密码错误");
        }
    }

    public Message updateChannelUsed(Long id) {
        LiveTaskUserChannel channel = (LiveTaskUserChannel)this.channelMapper.selectById(id);
        this.channelMapper.updateById((new LiveTaskUserChannel()).setId(id).setCreateUser(SessionInfo.getUserId()).setTimeUsed(channel.getTimeUsed() + 10));
        return new Message(true, "");
    }

    public LiveTaskUserChannel getChannelById(Long id) {
        return (LiveTaskUserChannel)this.channelMapper.selectById(id);
    }

    public void checkGoods(LiveTaskUserPut put) {
        this.taskUserDao.updateById((new LiveTaskUser()).setId(put.getTaskUserId()).setHasConnect(2));
        Long count = this.putDao.selectCount(new QueryWrapper((new LiveTaskUserPut()).setChannelId(put.getChannelId()).setProductId(put.getProductId())));
        if (count == 0l) {
            this.putDao.insert(put.setState(2).setCreateTime(System.currentTimeMillis()).setCrerateUser(SessionInfo.getUserId()));
        }

    }

    public Message getLiveContext(Long id) {
        return new Message(true, ((LiveExamTask)this.taskDao.selectById(id)).getTaskChara());
    }

    public List<LiveProduct> getLiveProductItems(Long id) {
        List<LiveProduct> products = this.productDao.selectProductsByTask(id);
        Iterator var3 = products.iterator();

        while(var3.hasNext()) {
            LiveProduct product = (LiveProduct)var3.next();
            product.setItems(this.itemDao.selectList(new QueryWrapper((new LiveProductItem()).setProductId(product.getId()))));
        }

        return products;
    }

    public Map<String, Object> initApp(String version) {
        Map<String, Object> res = new HashMap();
        res.put("reload", this.cacheService.getParam("SYSTEM_APP_RELOAD"));
        res.put("pushError", this.cacheService.getParam("SYSTEM_APP_PUSH_ERROR"));
        String desc = this.cacheService.getParam("SYSTEM_INDEX_TIP");
        String currentVersion = this.cacheService.getParam("APP_CURRENT_VERSION");
        if (!currentVersion.equals(version)) {
            res.put("hasNew", 1);
            res.put("downloadUrl", this.cacheService.getParam("APP_DOWNLOAD_URL"));
        } else {
            res.put("haseNew", 2);
        }

        String[] strs = desc.split("。");
        res.put("desc", JSONArray.of(strs).toString());
        res.put("uploadUrlPath", OpenService.uploadUrlPath);
        res.put("recordBitRate", this.cacheService.getParam("RECORD_BIT_RATE"));
        res.put("recordFrameRate", this.cacheService.getParam("RECORD_FRAME_RATE"));
        res.put("recordNeed", this.cacheService.getParam("RECORD_NEED"));
        User user = SessionInfo.getUser();
        res.put("needFrameRate", user.getOpenId());
        res.put("imageMode", this.cacheService.getParam("IMAGE_MODE"));
        return res;
    }

    public Message doResetExam(Long id, Long leuId) throws Exception {
        String param = this.cacheService.getParam("SYSTEM_APP_RELOAD");
        if ("1".equals(param)) {
            LiveExamUser liveExamUser = (LiveExamUser)this.examUserDao.selectById(leuId);
            if (liveExamUser == null) {
                throw new Exception("重置失败");
            } else if (!liveExamUser.getCreateUser().equals(SessionInfo.getUserId())) {
                throw new Exception("重置失败");
            } else {
                List<LiveTaskUserChannel> channels = this.channelMapper.selectList(new QueryWrapper((new LiveTaskUserChannel()).setTaskUserId(leuId)));
                List<String> files = new ArrayList();
                if (channels.size() > 0) {
                    files = (List)channels.stream().map((e) -> {
                        return e.getStoreFileName();
                    }).collect(Collectors.toList());
                }

                String sql = "delete aa.*  from live_barrage_channel aa where aa.channel_id in (select a.id from live_task_user_channel a where a.task_user_id in (select b.id from live_task_user b where b.leu_id = ?))";
                System.out.println(sql);
                this.jdbcTemplate.update(sql, new Object[]{leuId});
                sql = "delete a.*  from live_task_user_detail a where a.task_user_id in (select b.id from live_task_user b where b.leu_id = ?)";
                this.jdbcTemplate.update(sql, new Object[]{leuId});
                sql = "delete a.*  from live_task_user_channel a where a.task_user_id in (select b.id from live_task_user b where b.leu_id = ?)";
                this.jdbcTemplate.update(sql, new Object[]{leuId});
                sql = "delete a.*  from live_task_user a where a.leu_id = ?";
                this.jdbcTemplate.update(sql, new Object[]{leuId});
                sql = "delete a.*  from live_exam_user a where a.id = ?";
                this.jdbcTemplate.update(sql, new Object[]{leuId});
                return new Message(true, JSONArray.of(files).toString());
            }
        } else {
            return new Message(false, "重置失败");
        }
    }

    public Message getReconnectChannel(Long channelId) {
        List<LiveServer> servers = this.serverDao.selectList(new QueryWrapper((new LiveServer()).setState(1)));
        LiveServer server = null;

        try {
            server = (LiveServer)servers.get(channelIndex % servers.size());
            Integer var4 = channelIndex;
            channelIndex = channelIndex + 1;
        } catch (Exception var6) {
            var6.printStackTrace();
            server = (LiveServer)servers.get(0);
        }

        String channelName = UUID.randomUUID().toString().replaceAll("-", "");
        String url = "rtmp://" + server.getServerIp() + ":" + server.getServerPort() + "/mapper/" + channelName;
        return new Message(true, url);
    }

    public void saveChannelRecord(Long channelId, String filePath) {
        this.channelMapper.updateById((new LiveTaskUserChannel()).setId(channelId).setStoreFileName(filePath));
    }

    public Message judgeUploadState(Long channelId) {
        Integer state = ((LiveTaskUserChannel)this.channelMapper.selectById(channelId)).getUploadState();
        return new Message(true, state + "");
    }

    public void doChangeUserState() {
        User user = (User)this.userDao.selectById(SessionInfo.getUserId());
        this.userDao.updateById((new User()).setId(user.getId()).setOpenId("noneed".equals(user.getOpenId()) ? "need" : "noneed"));
    }

    public Map<Long, List<LiveBarrage>> getAllQuestions(Long examId) {
        Map<Long, List<LiveBarrage>> res = new HashMap();
        List<LiveExamTask> tasks = this.taskDao.selectList(new QueryWrapper((new LiveExamTask()).setTaskType(1).setExamId(examId)));
        String sql = "select * from live_barrage where type = 5 and product_id = ?";
        Iterator var5 = tasks.iterator();

        while(var5.hasNext()) {
            LiveExamTask task = (LiveExamTask)var5.next();
            List<LiveBarrage> list = this.jdbcTemplate.query(sql, new Object[]{task.getTaskProductId()}, new BeanPropertyRowMapper(LiveBarrage.class));
            res.put(task.getTaskProductId(), list);
        }

        return res;
    }

    public Map<String, Integer> getRecordParams() {
        Map<String, Integer> res = new HashMap();
        User user = (User)this.userDao.selectById(SessionInfo.getUserId());
        res.put("recordWidth", 720);
        res.put("recordHeight", 1280);
        res.put("recordBitRate", 1658880);
        if (!ICommons.isNullOrEmpty(user.getRecordWidth())) {
            res.put("recordWidth", user.getRecordWidth());
        }

        if (!ICommons.isNullOrEmpty(user.getRecordHeight())) {
            res.put("recordHeight", user.getRecordHeight());
        }

        if (!ICommons.isNullOrEmpty(user.getRecordBitRate())) {
            res.put("recordBitRate", user.getRecordBitRate());
        }

        return res;
    }
}
